package com.aldobucchi.ds.op
{
	
	import com.aldobucchi.ds.DataStructureEvent;
	import com.aldobucchi.ds.container.ContainerDiff;
	import com.aldobucchi.ds.container.IRContainer;
	

	public class AbstractContainerBestOp extends AbstractContainerToElementOp
	{

		


		/**
		 * 
		 * 
		 * 
		 * 
		 * @param iContainer
		 * @param iCompareFunction
		 * @param iValueHandlerFunction
		 * @param emptyValue
		 * 
		 */
		public function AbstractContainerBestOp( iContainer:IRContainer, iValueHandlerFunction:Function, emptyValue:* )
		{
			
			super( iContainer, iValueHandlerFunction, emptyValue );
		}
		
		
		
		override protected function batch( ):void
		{
			refresh( );	
		}
		
		
		private function refresh( ):void
		{

			if ( iContainer.size == 0 )
			{
				updateElement( emptyValue );
			}
			else
			{
				updateElement( findBest( iContainer ) );				
			}		
		
		}
		
		
		
		override protected function iContainer_change( event:DataStructureEvent ):void
		{
		
			var diff:ContainerDiff = event.diff as ContainerDiff;
			
			// was a bigger element added?
			var best:* = findBest( diff.addedElements, currentElement );
			
			if ( best !== currentElement ) // yes, there a bigger element was added
			{
				updateElement( best );
				return;			
			}
			
			// is the current element still contained?
			if ( ! iContainer.contains( currentElement ) )
			{
				refresh( ); // this should be optimized ( using an internal balanced tree ? )
							// for now we are traversing the whole structure
			}
		
		}
		
		
		
		
		/**
		 * 
		 * Checks the elements container to see if there is a better match ( better than best so far )
		 * and returns that match
		 * 
		 * @param elements
		 * @param bestSoFar
		 * @return 
		 * 
		 */		
		protected function findBest( elements:IRContainer, bestSoFar:* = undefined ):*
		{
		
		
		}
		
		
	}
	
}